
import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:single/event/door_status_event.dart';
import 'package:single/event/index_refresh_event.dart';
import '../entity/book_entity.dart';
import '../event/inventory_event.dart';
import '../hive/hive_helper.dart';
import '../http/api.dart';
import '../main.dart';
import '../serial/send_helper.dart';
import '../util/toast_util.dart';


class StackBook extends StatefulWidget {
  const StackBook({Key? key}) : super(key: key);

  @override
  State<StackBook> createState() => _StackBookState();
}

class _StackBookState extends State<StackBook> {

  StreamSubscription? lockSubscription;
  StreamSubscription? actionSubscription;

  RxList<BookEntity> bookList = RxList();


  @override
  initState() {
    super.initState();
    lockSubscription = eventFactory.on<DoorStatusEvent>().listen((event) {
      if(!event.isOpen){
        timer.cancel();
        BotToast.showLoading();
        hfSerialPortHelper.sendData(inventory());
      }
    });

    actionSubscription = eventFactory.on<InventoryEvent>().listen((event) {
      BotToast.closeAllLoading();
      _analysis(event.data);
    });

  }

  _analysis(List<String> data) async {
    // if(data.isNotEmpty) {
      bookList.clear();
      var books = bookQueryAll().where((element) => element.statue==0);
      for (var item in books) {
        item.stackStatus = 2;
        bookList.add(item);
      }
      for (var item in data) {
        try{
          var length = int.parse(item.substring(0,2));
          var bookNo = item.substring(2, length+2);
          getBook(bookNo);

        }catch(e){
          var bk = BookEntity();
          bk.no = item;
          bk.stackStatus = -1;
          bookList.add(bk);
          toastWarn('条码号异常');
        }
      }
    // }
  }

  getBook(bookNo)  async {
    var bk = bookQuery(bookNo);

    if(bk != null &&  bk.statue == 0){
      bookList.removeWhere((element) => element.no == bookNo);
      bk.stackStatus = 1;
      bookList.add(bk);
    }

    if(bk != null && bk.statue == 1){
      bk.stackStatus = 0;
      bookList.add(bk);
    }

    if(bk == null){
      var data = await findBook(bookNo);
      if(data != null){
        data.stackStatus = 0;
        data.cover = '';
        data.summary = '';
        bookList.add(data);
      }else{
        var bk = BookEntity();
        bk.no = bookNo;
        bk.stackStatus = -2;
        bookList.add(bk);
      }
    }

  }


  @override
  void dispose() {
    super.dispose();
    actionSubscription?.cancel();
    actionSubscription = null;
    lockSubscription?.cancel();
    lockSubscription = null;
  }

  _title(){
    return Container(
        margin: EdgeInsets.only(left: 12.w,right: 12.w),
        width: double.infinity,
        height: 60.h,
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [

            Positioned(
              left: 0,
              child:  InkWell(
                onTap: (){
                  Get.back();
                },
                child: Image.asset("assets/images/back.png",width:80.w, fit: BoxFit.fitWidth,),
              ),
            ),
            Text("图书整理",style: TextStyle(color: const Color.fromRGBO(29, 125, 168, 1),fontSize: 16.sp,fontWeight: FontWeight.bold),),

          ],
        )
    );
  }


  _divider(){
    return Divider(
      height: 0.5.h, // Divider 组件高度
      indent: 4.w, // 分割线左侧间距
      endIndent: 4.w, // 分割线右侧间距
      color: const Color.fromRGBO(86, 169, 255, 1),
    );
  }

  _listLabel(){
    return Container(
        padding: EdgeInsets.only(top: 2.h,bottom: 2.h),
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
        child: Row(
          // mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _label('序号',50.w),
            _label('图书条码号',125.w),
            _label('图书名称',135.w),
            _label('状态',50.w),
          ],
        )
    );
  }

  _label(text,width){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: Colors.blueAccent,fontSize: 10.sp),textAlign: TextAlign.center,),
    );
  }

  _listTitle(){
    return Container(
      // width: 300.w,
      height: 20.h,
      decoration: BoxDecoration(
        color: const Color.fromRGBO(86, 169, 255, 1),
        borderRadius: BorderRadius.only(topLeft:Radius.circular(4.r),topRight: Radius.circular(4.r)),
      ),
      alignment: Alignment.center,
      child: Text('图书清单',style: TextStyle(color: Colors.white,fontSize: 10.sp,fontWeight: FontWeight.bold),),
    );
  }

  _item(text,width,{Color color = Colors.black}){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: color,fontSize: 8.sp),textAlign: TextAlign.center,),
    );
  }

  _listItem(list,index){
    var item = list[index];
    return Container(
        padding: EdgeInsets.only(top: 2.h,bottom: 2.h),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _item('${index+1}',50.w),
            _item('${item.no}',125.w),
            _item('${item.mainTitle}',135.w),
            item.stackStatus == 0?_item('上架',50.w,color: Colors.blue):item.stackStatus == 1?
              _item('在架',50.w):item.stackStatus == 2?_item('下架',50.w,color: Colors.red):
            item.stackStatus == -1?_item('条码号错误',50.w,color: Colors.deepOrangeAccent):_item('图书未注册',50.w,color: Colors.deepOrangeAccent),
          ],
        )
    );
  }

  _bList(){
    return Obx(() => Expanded(child: ListView.separated(
      itemBuilder: (context, index) {
        return _listItem(bookList,index);
      },
      itemCount: bookList.length,
      separatorBuilder: (BuildContext context, int index) {
        return Divider(
          height: 0.5.h, // Divider 组件高度
          // thickness: 5, // 分割线线宽，分割线居于 Divider 中心
          indent: 4.w, // 分割线左侧间距
          endIndent: 4.w, // 分割线右侧间距
          color: Colors.grey,
        );
      },
    )));
  }

  _totalWidget(){

    return Obx(() => Container(
      margin: EdgeInsets.only(top: 5.h, bottom: 5.h),
      child: Row(
        children: [
          Text('   在架${ bookList.where((e) => e.stackStatus==1).length}本   ',style: TextStyle(fontSize: 8.sp)),
          Text('下架${ bookList.where((e) => e.stackStatus==2).length}本   ',style: TextStyle(color: Colors.red,fontSize: 8.sp),),
          Text('上架${ bookList.where((e) => e.stackStatus==0).length}本   ',style: TextStyle(color: Colors.blue,fontSize: 8.sp),),
          Text('条码号错误${ bookList.where((e) => e.stackStatus==-1).length}本   ',style: TextStyle(color: Colors.deepOrangeAccent,fontSize: 8.sp),),
          Text('图书未注册${ bookList.where((e) => e.stackStatus==-2).length}本   ',style: TextStyle(color: Colors.deepOrangeAccent,fontSize: 8.sp),),
        ],
      ),
    ));
  }

  _listWidget(){
    return Container(
      width: 380.w,
      height: 500.h,
      margin: EdgeInsets.only(left: 12.w,right: 12.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      child: Column(
        children: [
          _listTitle(),
          _listLabel(),
          _divider(),
          _bList(),
          _totalWidget(),
        ],
      ),

    );
  }

  _action(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        InkWell(
          onTap: () {
            hfSerialPortHelper.sendData(openDoor());

          },
          child:  Image.asset("assets/images/open_door.png", width:100.w, fit: BoxFit.fitWidth,),
        ),
        InkWell(
          onTap: () {
            for(var item in bookList){
              if(item.stackStatus == 0){
                item.statue = 0;
                bookInsert(item.no, item);
              }
              if(item.stackStatus == 2){
                bookDelete(item.no);
              }
            }
            eventFactory.fire(IndexRefreshEvent());
            Get.back();
          },
          child:  Image.asset("assets/images/confirm.png", width:100.w, fit: BoxFit.fitWidth,),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
            color: Color.fromRGBO(242,254, 255, 1)
        ),
        child: Column(
          children: [
            _title(),
            Align(child: _listWidget(),),
            _action()
          ],
        ),
      ),
    );
  }
}


